<template>
  <div class="generate-report-step">
    <a-typography-title :heading="4">步骤3: 诊断报告生成</a-typography-title>
    
    <div class="step-container">
      <div class="report-section">
        <div class="section-title">
          <icon-file />
          <span>诊断报告预览</span>
        </div>
        
        <div v-if="generationStatus === 'waiting'" class="empty-report">
          <a-empty description="点击开始生成按钮，AI将基于CT图像和病历报告生成诊断建议" />
          <a-button type="primary" size="large" @click="startGeneration">开始生成</a-button>
        </div>
        
        <div v-else-if="generationStatus === 'processing'" class="processing-report">
          <a-spin tip="AI正在分析数据并生成诊断报告，请稍候..." />
          <a-progress 
            :percent="generationProgress / 100" 
            :animation="true"
            status="normal"
          >
            <template v-slot:text="scope">
              {{ Math.round(scope.percent * 100) }}%
            </template>
          </a-progress>
        </div>
        
        <div v-else-if="generationStatus === 'completed'" class="report-content">
          <a-tabs>
            <a-tab-pane key="1" title="报告编辑">
              <div class="report-editor">
                <a-form :model="reportForm" layout="vertical">
                  <a-form-item field="title" label="报告标题">
                    <a-input v-model="reportForm.title" placeholder="请输入报告标题" />
                  </a-form-item>
                  
                  <a-form-item field="patientInfo" label="患者信息">
                    <a-textarea v-model="reportForm.patientInfo" placeholder="请输入患者信息" :auto-size="{ minRows: 3, maxRows: 5 }" />
                  </a-form-item>
                  
                  <a-form-item field="clinicalFindings" label="临床发现">
                    <a-textarea v-model="reportForm.clinicalFindings" placeholder="请输入临床发现" :auto-size="{ minRows: 3, maxRows: 5 }" />
                  </a-form-item>
                  
                  <a-form-item field="imagingFindings" label="影像学发现">
                    <a-textarea v-model="reportForm.imagingFindings" placeholder="请输入影像学发现" :auto-size="{ minRows: 4, maxRows: 6 }" />
                  </a-form-item>
                  
                  <a-form-item field="diagnosis" label="诊断结论">
                    <a-textarea v-model="reportForm.diagnosis" placeholder="请输入诊断结论" :auto-size="{ minRows: 3, maxRows: 5 }" />
                  </a-form-item>
                  
                  <a-form-item field="recommendations" label="治疗建议">
                    <a-textarea v-model="reportForm.recommendations" placeholder="请输入治疗建议" :auto-size="{ minRows: 3, maxRows: 5 }" />
                  </a-form-item>
                  
                  <a-form-item field="doctorInfo" label="医生信息">
                    <a-input v-model="reportForm.doctorInfo" placeholder="请输入医生信息" />
                  </a-form-item>
                </a-form>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" title="报告预览">
              <div id="reportContentDiv" class="report-preview" ref="reportContent">
                <div class="report-header">
                  <h2>{{ reportForm.title }}</h2>
                  <div class="report-meta">
                    <span>报告日期: {{ new Date().toLocaleDateString() }}</span>
                    <span>报告编号: R{{ new Date().getTime().toString().slice(-8) }}</span>
                  </div>
                </div>
                
                <div class="report-section-content">
                  <h3>患者信息</h3>
                  <div class="section-content">{{ reportForm.patientInfo }}</div>
                </div>
                
                <div class="report-section-content">
                  <h3>临床发现</h3>
                  <div class="section-content">{{ reportForm.clinicalFindings }}</div>
                </div>
                
                <div class="report-section-content">
                  <h3>影像学发现</h3>
                  <div class="section-content">{{ reportForm.imagingFindings }}</div>
                </div>
                
                <div class="report-image-section">
                  <h3>CT影像</h3>
                  <div class="image-grid">
                    <div v-for="(image, index) in selectedImages" :key="index" class="ct-image-container">
                      <img :src="image.url" alt="CT影像" class="ct-image" />
                      <div class="image-caption">图{{ index + 1 }}: {{ image.description }}</div>
                    </div>
                  </div>
                </div>
                
                <div class="report-section-content">
                  <h3>诊断结论</h3>
                  <div class="section-content">{{ reportForm.diagnosis }}</div>
                </div>
                
                <div class="report-section-content">
                  <h3>治疗建议</h3>
                  <div class="section-content">{{ reportForm.recommendations }}</div>
                </div>
                
                <div class="report-footer">
                  <div class="hospital-info">
                    <div>医院：云南省第一人民医院呼吸内科</div>
                    <div>地址：云南省昆明市西山区金碧路157号</div>
                    <div>电话：0871-63638623</div>
                  </div>
                  <div class="doctor-signature">
                    <div>报告医生: {{ reportForm.doctorInfo }}</div>
                    <div>签名：________________</div>
                    <div>日期：{{ new Date().toLocaleDateString() }}</div>
                  </div>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        
        <div v-else-if="generationStatus === 'error'" class="error-report">
          <a-result status="error" title="报告生成失败" sub-title="请检查输入数据是否完整">
            <template #extra>
              <a-button type="primary" @click="startGeneration">重新生成</a-button>
            </template>
          </a-result>
        </div>
      </div>
      
      <div class="info-section">
        <div class="section-title">
          <icon-info-circle />
          <span>数据概览</span>
        </div>
        
        <a-descriptions :data="dataOverview" layout="vertical" />
        
        <a-divider />
        
        <div class="action-buttons">
          <a-space direction="vertical" style="width: 100%">
            <a-button 
              v-if="generationStatus === 'completed'" 
              type="primary" 
              @click="printReport"
            >
              <template #icon><icon-download /></template>
              打印报告
            </a-button>
            
            <a-button 
              v-if="generationStatus === 'completed'" 
              type="outline"
              @click="printInNewWindow" 
            >
              <template #icon><icon-download /></template>
              新窗口打印
            </a-button>
            
            <a-button 
              v-if="generationStatus === 'completed'" 
              type="outline" 
              status="success" 
              @click="completeWorkflow"
            >
              <template #icon><icon-check /></template>
              完成工作流
            </a-button>
            
            <a-button @click="goToPrevStep">
              <template #icon><icon-left /></template>
              返回上一步
            </a-button>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { 
  IconFile, 
  IconInfoCircle, 
  IconDownload,
  IconCheck,
  IconLeft
} from '@arco-design/web-vue/es/icon';
import { nextTick } from 'vue';
import { useWorkflowStore } from '@/stores/workflow';
import { diagnosisApi } from '@/services/api';

const props = defineProps({
  workflowData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['prev', 'complete']);
const workflowStore = useWorkflowStore();

// 报告生成状态：waiting, processing, completed, error
const generationStatus = ref('waiting');
const generationProgress = ref(0);

// 计算属性：确保进度百分比不超过100
const generationProgressPercent = computed(() => {
  return Math.min(generationProgress.value, 100);
});

// 报告表单数据
const reportForm = reactive({
  title: '肺部CT诊断报告',
  patientInfo: '',
  clinicalFindings: '',
  imagingFindings: '',
  diagnosis: '',
  recommendations: '',
  doctorInfo: '王医生 / 呼吸内科 / 主治医师'
});

// 报告内容的引用
const reportContent = ref<HTMLElement | null>(null);

// 选择的CT图像
interface CTImage {
  url: string;
  description: string;
}

const selectedImages = ref<CTImage[]>([]);

// 初始化CT图像
const initCTImages = () => {
  // 清空现有图像
  selectedImages.value = [];
  
  // 检查是否有分割结果
  if (props.workflowData.ctUpload && props.workflowData.ctUpload.segmentationResults && props.workflowData.ctUpload.segmentationResults.length > 0) {
    const segResults = props.workflowData.ctUpload.segmentationResults;
    
    // 添加原始图像
    if (segResults[0].originalUrl) {
      selectedImages.value.push({
        url: segResults[0].originalUrl,
        description: '原始CT图像'
      });
    }
    
    // 添加分割叠加图
    if (segResults[0].overlayUrl || segResults[0].segmentedUrl) {
      selectedImages.value.push({
        url: segResults[0].overlayUrl || segResults[0].segmentedUrl,
        description: '分割叠加结果'
      });
    }
    
    // 添加分割掩码图
    if (segResults[0].maskUrl) {
      selectedImages.value.push({
        url: segResults[0].maskUrl,
        description: '分割掩码'
      });
    }
  }
  
  // 如果没有找到图像，则使用占位图
  if (selectedImages.value.length === 0) {
    selectedImages.value = [
      {
        url: 'https://via.placeholder.com/300x300?text=CT+Image+1',
        description: '未找到CT图像'
      }
    ];
  }
  
  console.log('报告中的图像：', selectedImages.value);
};

// 数据概览
const dataOverview = computed(() => {
  return [
    {
      label: '患者姓名',
      value: props.workflowData.patientInfo?.name || '未知'
    },
    {
      label: '患者ID',
      value: props.workflowData.patientInfo?.id || '未知'
    },
    {
      label: 'CT图像数量',
      value: props.workflowData.ctImages?.length || 0
    },
    {
      label: '分割结果数量',
      value: props.workflowData.segmentationResults?.length || 0
    },
    {
      label: '病历报告',
      value: props.workflowData.medicalRecord ? '已上传' : '未上传'
    },
    {
      label: 'CTClip预测',
      value: ctClipPrediction.value ? '已生成' : '未生成'
    },
    {
      label: '预测内容',
      value: ctClipPrediction.value || '无预测内容'
    }
  ];
});

// 开始生成报告
const startGeneration = async () => {
  if (!ctClipPrediction.value) {
    Message.warning('缺少CTClip预测结果，无法生成完整诊断报告');
    return;
  }

  generationStatus.value = 'processing';
  generationProgress.value = 0;
  
  try {
    // 设置初始进度
    generationProgress.value = 10;

    // 准备电子病历数据
    const electronicRecord = {
      patient_id: props.workflowData.patientInfo?.id || 'PT-UNKNOWN',
      name: props.workflowData.patientInfo?.name || '未知',
      gender: props.workflowData.patientInfo?.gender || '未知',
      age: parseInt(props.workflowData.patientInfo?.age) || 0,
      medical_history: {
        smoking: props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '吸烟史')?.value || '未知',
        family_history: props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '家族病史')?.value || '无',
        comorbidities: props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '伴随疾病')?.value?.split('、') || []
      },
      symptoms: props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '主要症状')?.value?.split('、') || []
    };

    generationProgress.value = 30;

    // 调用API生成诊断报告
    const result = await diagnosisApi.generateDiagnosisReport(
      ctClipPrediction.value, 
      electronicRecord
    );

    generationProgress.value = 90;

    if (result.success) {
      // 将生成的报告填充到表单中
      reportForm.patientInfo = `姓名: ${electronicRecord.name}, 性别: ${electronicRecord.gender}, 年龄: ${electronicRecord.age}\n患者ID: ${electronicRecord.patient_id}, 科室: ${props.workflowData.patientInfo?.department || '未知'}`;
      
      reportForm.clinicalFindings = `患者主诉${electronicRecord.symptoms.join('、')}。${props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '症状详情')?.value || ''}`;
      
      // 使用CTClip的预测结果作为影像学发现的一部分
      reportForm.imagingFindings = `CT检查显示：${ctClipPrediction.value}\n\n${props.workflowData.medicalRecord?.extractedInfo?.find(item => item.label === '影像学表现')?.value || ''}`;
      
      // 处理诊断报告内容，避免重复
      let diagnosisReport = result.diagnosis_report || '';
      
      // 检查是否包含"诊断："和"治疗建议："部分
      if (diagnosisReport.includes('诊断：') && diagnosisReport.includes('治疗建议：')) {
        // 分割报告内容
        const parts = diagnosisReport.split('治疗建议：');
        
        // 提取诊断结论（去掉"诊断："前缀）
        reportForm.diagnosis = parts[0].replace('诊断：', '').trim();
        
        // 提取治疗建议
        reportForm.recommendations = parts[1].trim();
      } else {
        // 如果没有明确的分隔，则将整个报告作为诊断结论
        reportForm.diagnosis = diagnosisReport;
        reportForm.recommendations = '请根据患者情况制定个性化治疗方案';
      }
      
      // 保存到store
      workflowStore.saveDiagnosisReport({
        reportForm: { ...reportForm },
        generatedAt: new Date().toISOString(),
        reportId: `R${new Date().getTime().toString().slice(-8)}`
      });
      
      generationProgress.value = 100;
      generationStatus.value = 'completed';
      Message.success('诊断报告生成成功');
    } else {
      throw new Error('生成诊断报告失败');
    }
  } catch (error) {
    console.error('报告生成出错:', error);
    generationStatus.value = 'error';
    Message.error('诊断报告生成失败: ' + (error as Error).message);
  }
};

// 预加载图片
const preloadImages = async () => {
  return new Promise<void>((resolve) => {
    // 如果没有图片，直接完成
    if (selectedImages.value.length === 0) {
      resolve();
      return;
    }

    let loadedCount = 0;
    const totalImages = selectedImages.value.length;

    // 监听每个图片的加载
    selectedImages.value.forEach(image => {
      const img = new Image();
      img.onload = () => {
        loadedCount++;
        if (loadedCount === totalImages) {
          resolve(); // 所有图片加载完成
        }
      };
      img.onerror = () => {
        console.error('图片加载失败:', image.url);
        loadedCount++;
        if (loadedCount === totalImages) {
          resolve(); // 所有图片加载完成（即使有错误）
        }
      };
      img.src = image.url;
    });

    // 设置超时，防止无限等待
    setTimeout(() => {
      resolve();
    }, 5000); // 最多等待5秒
  });
};

// 将图片转换为Base64，解决跨域问题
const convertImagesToBase64 = async () => {
  try {
    // 找到所有报告中的图片
    const reportDiv = document.getElementById('reportContentDiv');
    if (!reportDiv) return;
    
    const images = reportDiv.querySelectorAll('img');
    if (!images || images.length === 0) return;
    
    Message.info(`正在处理报告中的${images.length}张图片，请稍候...`);
    
    for (let i = 0; i < images.length; i++) {
      const img = images[i] as HTMLImageElement;
      
      if (!img.src || img.src.startsWith('data:')) continue;
      
      try {
        // 创建一个新的img元素，用于绘制到canvas
        const tempImg = new Image();
        tempImg.crossOrigin = 'anonymous'; // 尝试解决跨域问题
        
        // 使用promise等待图片加载
        await new Promise<void>((resolve, reject) => {
          tempImg.onload = () => {
            try {
              // 创建canvas并绘制图片
              const canvas = document.createElement('canvas');
              canvas.width = tempImg.width || 300;
              canvas.height = tempImg.height || 300;
              const ctx = canvas.getContext('2d');
              
              if (ctx) {
                // 绘制图片到canvas
                ctx.fillStyle = '#fff';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(tempImg, 0, 0, canvas.width, canvas.height);
                
                // 获取base64数据
                const base64 = canvas.toDataURL('image/png');
                
                // 替换原始图片的src
                img.src = base64;
                img.setAttribute('data-processed', 'true');
                console.log(`图片${i+1}处理完成`);
              }
            } catch (e) {
              console.error('处理图片出错:', e);
            }
            resolve();
          };
          
          tempImg.onerror = () => {
            console.error(`无法加载图片: ${img.src}`);
            resolve(); // 继续处理其他图片
          };
          
          // 设置src触发加载
          tempImg.src = img.src;
        });
      } catch (e) {
        console.error(`处理图片${i+1}出错:`, e);
      }
    }
    
    Message.success('图片处理完成，现在可以打印了');
  } catch (e) {
    console.error('转换图片过程出错:', e);
    Message.error('处理图片时出错，打印可能无法显示部分图片');
  }
};

// 打印报告前准备
const preparePrint = async () => {
  try {
    // 预加载图片
    await preloadImages();
    
    // 转换图片为Base64
    await convertImagesToBase64();
    
    return true;
  } catch (e) {
    console.error('准备打印时出错:', e);
    Message.error('准备打印时出错');
    return false;
  }
};

// 打印报告
const printReport = async () => {
  Message.loading('正在准备打印，请稍候...');
  
  // 切换到报告预览标签页
  const tabPanes = document.querySelectorAll('.arco-tabs-header-title');
  if (tabPanes && tabPanes.length > 1) {
    (tabPanes[1] as HTMLElement).click();
  }
  
  // 准备打印（包括处理图片）
  const ready = await preparePrint();
  if (!ready) {
    Message.error('打印准备失败，请重试');
    return;
  }
  
  // 确保内容已完全加载
  setTimeout(() => {
    // 先展开报告内容
    const reportDiv = document.getElementById('reportContentDiv');
    if (reportDiv) {
      // 强制设置可见性
      reportDiv.style.display = 'block';
      reportDiv.style.visibility = 'visible';
      
      // 浏览器打印对话框
      setTimeout(() => {
        window.print();
        Message.success('打印对话框已打开，请选择"另存为PDF"选项');
      }, 500);
    } else {
      Message.error('无法找到报告内容');
    }
  }, 500);
};

// 在新窗口中打印
const printInNewWindow = async () => {
  Message.loading('正在准备新窗口打印，请稍候...');
  
  // 准备打印（包括处理图片）
  const ready = await preparePrint();
  if (!ready) {
    Message.error('打印准备失败，请重试');
    return;
  }
  
  // 获取报告内容
  const reportDiv = document.getElementById('reportContentDiv');
  if (!reportDiv) {
    Message.error('无法获取报告内容');
    return;
  }
  
  // 创建一个新窗口
  const printWindow = window.open('', '_blank', 'width=800,height=600');
  if (!printWindow) {
    Message.error('无法创建打印窗口，请检查浏览器是否阻止了弹出窗口');
    return;
  }
  
  // 准备完整的HTML内容
  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>${reportForm.title}</title>
      <meta charset="utf-8">
      <style>
        body {
          font-family: Arial, sans-serif;
          line-height: 1.6;
          color: #333;
          padding: 20px;
          margin: 0;
        }
        .report-header {
          text-align: center;
          margin-bottom: 20px;
          padding-bottom: 10px;
          border-bottom: 2px solid #333;
        }
        .report-header h2 {
          font-size: 24px;
          margin-bottom: 10px;
        }
        .report-meta {
          display: flex;
          justify-content: space-between;
          color: #666;
          font-size: 12px;
        }
        .report-section-content {
          margin-bottom: 20px;
        }
        .report-section-content h3 {
          font-size: 18px;
          margin-bottom: 10px;
          color: #333;
        }
        .section-content {
          white-space: pre-line;
          line-height: 1.8;
        }
        .image-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;
          margin: 20px 0;
        }
        .ct-image-container {
          text-align: center;
        }
        .ct-image {
          max-width: 100%;
          height: auto;
          border: 1px solid #ddd;
        }
        .image-caption {
          margin-top: 5px;
          font-size: 12px;
          color: #666;
        }
        .report-footer {
          margin-top: 30px;
          padding-top: 10px;
          border-top: 1px solid #333;
          display: flex;
          justify-content: space-between;
        }
        .hospital-info {
          font-size: 12px;
          color: #666;
          line-height: 1.5;
        }
        .doctor-signature {
          text-align: right;
          font-size: 14px;
          line-height: 1.8;
        }
        @media print {
          body {
            padding: 0;
          }
          button {
            display: none;
          }
        }
      </style>
    </head>
    <body>
      ${reportDiv.innerHTML}
      <div style="text-align: center; margin-top: 20px;">
        <button onclick="window.print()">打印此页面</button>
      </div>
    </body>
    </html>
  `;
  
  // 写入内容到新窗口
  printWindow.document.open();
  printWindow.document.write(htmlContent);
  printWindow.document.close();
  
  // 等待内容加载完成
  setTimeout(() => {
    printWindow.focus();
    Message.success('新窗口已打开，请点击窗口中的"打印此页面"按钮');
  }, 500);
};

// 完成工作流
const completeWorkflow = () => {
  emit('complete', {
    reportForm,
    generatedAt: new Date().toISOString(),
    reportId: `R${new Date().getTime().toString().slice(-8)}`
  });
  
  Message.success('工作流已完成');
};

// 返回上一步
const goToPrevStep = () => {
  emit('prev');
};

// 确保在创建组件时就初始化
onMounted(() => {
  // 检查数据完整性
  if (!props.workflowData.ctImages?.length || !props.workflowData.medicalRecord) {
    Message.warning('数据不完整，请确保CT图像和病历报告已上传');
  }
  
  // 初始化CT图像
  initCTImages();
});

// CTClip预测结果的计算属性
const ctClipPrediction = computed(() => {
  return workflowStore.topCtClipPrediction || '';
});
</script>

<style scoped>
.generate-report-step {
  padding: var(--spacing-md) 0;
}

.step-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: var(--spacing-xl);
}

.section-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-weight: 600;
  font-size: 16px;
  margin-bottom: var(--spacing-md);
  color: var(--color-text-1);
}

.report-section, .info-section {
  background-color: var(--color-bg-2);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-report, .processing-report, .error-report {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  gap: var(--spacing-lg);
}

.report-content {
  flex: 1;
  min-height: 600px;
  overflow: auto;
}

.report-editor {
  padding: var(--spacing-md);
}

.report-preview {
  padding: var(--spacing-lg);
  border: 1px solid var(--color-border-2);
  border-radius: var(--radius-md);
  background-color: #fff;
  min-height: 600px;
}

.report-header {
  text-align: center;
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--color-border-3);
}

.report-header h2 {
  margin-bottom: var(--spacing-sm);
  font-size: 20px;
}

.report-meta {
  display: flex;
  justify-content: space-between;
  color: var(--color-text-3);
  font-size: 12px;
}

.report-section-content {
  margin-bottom: var(--spacing-lg);
}

.report-section-content h3 {
  font-size: 16px;
  margin-bottom: var(--spacing-sm);
  color: var(--color-text-1);
  font-weight: 600;
}

.section-content {
  white-space: pre-line;
  line-height: 1.8;
  color: var(--color-text-2);
}

.report-footer {
  margin-top: var(--spacing-xl);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--color-border-2);
  display: flex;
  justify-content: space-between;
}

.doctor-info {
  font-style: italic;
  color: var(--color-text-2);
}

.action-buttons {
  margin-top: var(--spacing-lg);
}

:deep(.arco-space-vertical) {
  width: 100%;
}

:deep(.arco-btn) {
  width: 100%;
  margin-bottom: var(--spacing-sm);
}

.progress-container {
  width: 100%;
  height: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-top: 16px;
  position: relative;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: var(--color-primary);
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
}

.custom-progress {
  width: 100%;
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin-top: 8px;
  overflow: hidden;
}

.custom-progress-bar {
  height: 100%;
  background-color: #2080f0;
  border-radius: 4px;
  transition: width 0.2s ease;
}

/* 医疗报告专用样式 */
.report-image-section {
  margin-bottom: var(--spacing-lg);
  border: 1px solid var(--color-border-2);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  background-color: var(--color-bg-1);
}

.report-image-section h3 {
  font-size: 16px;
  margin-bottom: var(--spacing-md);
  color: var(--color-text-1);
  font-weight: 600;
  border-bottom: 1px solid var(--color-border-2);
  padding-bottom: var(--spacing-xs);
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-md);
  margin-top: var(--spacing-md);
}

.ct-image-container {
  border: 1px solid var(--color-border-3);
  border-radius: var(--radius-sm);
  overflow: hidden;
  background-color: #000;
  position: relative;
  aspect-ratio: 1 / 1;
}

.ct-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  font-size: 12px;
  line-height: 1.4;
}

.hospital-info {
  font-size: 12px;
  color: var(--color-text-3);
  line-height: 1.5;
}

.doctor-signature {
  text-align: right;
  font-size: 14px;
  color: var(--color-text-2);
  line-height: 1.8;
}

/* 打印样式优化 */
@media print {
  .report-preview {
    padding: 0;
    border: none;
    box-shadow: none;
    background-color: white;
  }
  
  .ct-image-container {
    page-break-inside: avoid;
    break-inside: avoid;
    width: 100%;
    max-width: 100%;
    height: auto;
    position: relative;
    border: 1px solid #000;
    margin-bottom: 10px;
  }
  
  .ct-image {
    width: 100% !important;
    max-width: 100% !important;
    height: auto !important;
    display: block !important;
    object-fit: contain !important;
    margin: 0 auto !important;
    page-break-inside: avoid !important;
  }
  
  .image-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    width: 100%;
  }
  
  img {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
    color-adjust: exact !important;
  }
  
  .report-section-content {
    page-break-inside: avoid;
    break-inside: avoid;
  }
  
  .report-header {
    text-align: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 2px solid #333;
  }
  
  .report-header h2 {
    font-size: 24px;
    margin-bottom: 10px;
    color: #000;
  }
  
  .report-meta {
    display: flex;
    justify-content: space-between;
    color: #555;
    font-size: 12px;
  }
  
  .report-section-content h3 {
    font-size: 18px;
    margin-bottom: 10px;
    color: #000;
    font-weight: bold;
  }
  
  .section-content {
    white-space: pre-line;
    line-height: 1.8;
    color: #000;
  }
  
  .report-footer {
    margin-top: 30px;
    padding-top: 10px;
    border-top: 1px solid #333;
    display: flex;
    justify-content: space-between;
  }
  
  /* 其他元素不显示 */
  .arco-tabs-header,
  .arco-btn,
  .action-buttons,
  .info-section {
    display: none !important;
  }
}
</style>

<style>
/* 全局打印样式 */
@media print {
  /* 重置基本样式 */
  * {
    -webkit-print-color-adjust: exact !important;
    color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
  
  /* 隐藏不需要的元素 */
  body > *:not(.app),
  .app .layout > *:not(.content),
  .content > *:not(.generate-report-step),
  .generate-report-step > *:not(.step-container),
  .step-container > *:not(.report-section),
  .report-section > *:not(.report-content),
  .report-content > .arco-tabs > *:not(.arco-tabs-content),
  .arco-tabs-content > *:not([key="2"]),
  .info-section,
  .arco-tabs-header {
    display: none !important;
  }
  
  /* 显示报告内容 */
  #reportContentDiv, #reportContentDiv * {
    visibility: visible !important;
    opacity: 1 !important;
    display: block;
  }
  
  #reportContentDiv {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    padding: 2cm;
    margin: 0;
    background-color: white;
    color: black;
  }
  
  .report-content {
    display: block !important;
  }
  
  /* 确保图片显示 */
  .ct-image-container {
    page-break-inside: avoid;
    break-inside: avoid;
    margin-bottom: 15px;
    display: block;
  }
  
  .ct-image {
    max-width: 100%;
    height: auto !important;
    max-height: 200px;
    object-fit: contain;
    display: block;
    margin: 0 auto;
  }
  
  .image-caption {
    position: static;
    background-color: transparent;
    color: #000;
    padding: 5px 0;
    text-align: center;
    font-size: 11px;
  }
  
  /* 确保内容不被截断 */
  .report-content, .report-preview {
    overflow: visible !important;
    height: auto !important;
    max-height: none !important;
  }
  
  /* 页面尺寸设置 */
  @page {
    size: A4 portrait;
    margin: 1cm;
  }
}
</style> 